import datetime

from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
from django.shortcuts import render
from rest_framework.generics import ListAPIView
from rest_framework.views import APIView

from common.django_utlis import APIResponse
from mysite.models import Announcement
from mysite.serializers import AnnouncementSer


def index(request):
    return render(request, "index.html")


def room(request, room_name):
    return render(request, "room.html", {"room_name": room_name})


def announcement(request):
    return render(request, "announcement.html")


class AnnouncementView(ListAPIView):
    queryset = Announcement.objects.filter(is_delete=False, expire_date__gte=datetime.datetime.now())
    serializer_class = AnnouncementSer


def websocket1(request):
    return render(request, "websocket1.html")


class WebSocketView(APIView):
    """
    get: 建立websocket连接
    post：推送消息
    """

    def get(self, request):
        return render(request, "websocket.html")

    def post(self, request):
        message = {
            "type": "push_message",  # type 绑定的是推送消息的绑定方法
            "message": {
                "code": 2000,
                "msg": "更新人员信息",
                "data": {
                    "id": 1,
                    "name": "zz",
                    "age": 26
                }
            }
        }
        channel_layer = get_channel_layer()
        # 异步在同步中使用，必须使用该方法包裹
        async_to_sync(channel_layer.group_send)(group="123", message=message)
        return APIResponse()
